using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using CodePlex.Resourceful;

namespace CodePlex.Resourceful.Amazon.S3
{
    public class ListBucketsResult : IEnumerable<Bucket>
    {

        private readonly ACLPrincipal _owner;
        private readonly ReadOnlyList<Bucket,string> _buckets;

        private ListBucketsResult(ACLPrincipal owner, IEnumerable<Bucket> buckets)
        {
            _owner = owner;
            _buckets = new ReadOnlyList<Bucket, string>(buckets, delegate(Bucket item)
            {
                return item.Name;
            });
        }

        public ACLPrincipal Owner
        {
            get
            {
                return _owner;
            }
        }

        public ReadOnlyList<Bucket, string> Buckets
        {
            get
            {
                return _buckets;
            }
        }



        public static ListBucketsResult Parse(XmlReader reader)
        {
            /*
<?xml version="1.0" encoding="UTF-8"?>
<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <Owner>
    <ID>bcaf1ffd86f41caff1a493dc2ad8c2c281e37522a640e161ca5fb16fd081034f</ID>
    <DisplayName>webfile</DisplayName>
  </Owner>
  <Buckets>
    <Bucket>
      <Name>quotes;/Name>
      <CreationDate>2006-02-03T16:45:09.000Z</CreationDate>
    </Bucket>
    <Bucket>
      <Name>samples</Name>
      <CreationDate>2006-02-03T16:41:58.000Z</CreationDate>
    </Bucket>
  </Buckets>
</ListAllMyBucketsResult>
             */

            List<Bucket> rt = new List<Bucket>();
            ACLPrincipal principal = null;

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "Owner")
                {
                    principal = S3Connection.ParseACLPrincipal(reader, "Owner");
                }

                if (reader.NodeType == XmlNodeType.Element && reader.Name == "Bucket")
                {
                    rt.Add(Bucket.Parse(reader));
                }
            }

            return new ListBucketsResult(principal, rt);
        }

        public IEnumerator<Bucket> GetEnumerator()
        {
            return this.Buckets.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

    }
}
